/*
   Assaults an application
   Created by Randall Maas, 2008
   Copyright (c) 2008-2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
   Inspired by http://www.mcsweeneys.net/2007/5/21rottman.html
*/
using System;
using System . Threading;
using System . Windows . Forms;
using System . Drawing ;
using System . Diagnostics;
using System . IO;

static partial class Program
{
   /// <summary>
   /// Name of the application / window to search for
   /// </summary>
   static string AppName;

   /// <summary>
   /// Window handle or process id to search for
   /// </summary>
   static IntPtr AppId;

   /// <summary>
   /// An internal variable used to signal when we should stop or exit
   /// </summary>
   static volatile int Shutdown = 0;

   /// <summary>
   /// The visible area of the window under test
   /// </summary>
   static RECT   WinRect;

   /// <summary>
   /// Window that receives the hot key events
   /// </summary>
   static HotKeyWindow HKW;

   /// <summary>
   /// Starting time of test
   /// </summary>
   static long BaseTime;

   [STAThread]
   static void Main(string[] Args)
   {
      // Check the arguments
      CmdLine(Args);

      // If the application is supposed to exit
      if (0 != Shutdown)
        return ;

      // The window we will be testing
      IntPtr Wnd ;

      // Bind hotkey
      using(HKW     = new HotKeyWindow())
      {
         // Register to get the Ctrl+F2 key press
         HKW . RegisterHotKey(Keys . F2 | Keys . Control,
           delegate (object sender, KeyEventArgs e)
           {
              Interlocked . Exchange(ref Shutdown, 1);
           });

         // Find window of the app we're going to test
         ISendPort Port = Win32 . CurrentFocusSendPort;
         if ((null == AppName || "" == AppName) && IntPtr . Zero == AppId)
           {
              Wnd = UserSelectWindow();
           }
          else
           {
              Wnd = FindWin(AppName, AppId);
              // If the window is minimized, we have to restore it
              Win32 . Normal(Wnd);
              Thread . Sleep(500);

              // We have to make the window the focus window now
              Win32 . SwitchTo(Wnd);
           }

         // Get a process object to allow tracking of a process exit
         using (Process P = Win32 . Process(Wnd))
         {
            P . Exited += delegate(object sender, EventArgs e)
              {
                 Interlocked . Exchange(ref Shutdown, 1);
              };

            // Sleep for a moment to let things stabilize
            Thread . Sleep(500);
            Console . WriteLine("Press Ctrl+F2 to stop.");
            BaseTime = Stopwatch.GetTimestamp();
            Log . WriteLine("{0},{1},{2}", BaseTime-Stopwatch.GetTimestamp(), TimebaseFrequency, Stopwatch . Frequency);
            // Find bounds of the window
            RefreshWinBounds(Wnd);
            Log . WriteLine("{0},{1},{2},{3}", BaseTime-Stopwatch.GetTimestamp(),Rect, WinRect.Width, WinRect.Height);

            // Randomly send events
            while (0 == Shutdown)
            {
               // Send random events
               SendRandomEvents(Port);
               // TODO: check that the window hasn't gone away
               // Update bounds of the window (events can change it)
               RefreshWinBounds(Wnd);
               // TODO: check that the window isn't too small
            }
         }
      }
   }


   /// <summary>
   /// Gets the bounds of a window
   /// </summary>
   /// <param name="Win"></param>
   /// <returns></returns>
   static bool RefreshWinBounds(IntPtr Win)
   {
      // Find bounds of the window
      if (!Win32 . GetWindowRect(Win, out WinRect))
        return false;

      // Fix it to be in the scale of 0..65535 rather than screen dimensions
      // grab the size of the current monitor
      Rectangle region = Screen . PrimaryScreen . Bounds;
      double XScale = 65535.0 / (region . Right  - region . X);
      double YScale = 65535.0 / (region . Bottom - region . Y);
      if (true)
        {
           // We trim off a bit of an area on the edges to prevent closing or maximizing the window
           WinRect . Left  = (int) ((WinRect . Left + 4)  * XScale) ;
           WinRect . Right = (int) ((WinRect . Right- 4) * XScale) ;
           WinRect . Top   = (int) ((WinRect . Top + 16) * YScale) ;
           WinRect . Bottom= (int) ((WinRect . Bottom-4) * YScale) ;
        }
       else
        {
           MaxKey = 256;
           WinRect . Left  = (int) ((WinRect . Left )  * XScale) ;
           WinRect . Right = (int) ((WinRect . Right) * XScale) ;
           WinRect . Top   = (int) ((WinRect . Top  ) * YScale) ;
           WinRect . Bottom= (int) ((WinRect . Bottom) * YScale) ;
        }

      // Return success
      return true;
   }


}

